import * as Cesium from "cesium";
import BaseDraw from "./BaseDraw";
/**
 * 派生类-绘制点- 计算两点之间的高度差
 */
export default class DrawPointHeight extends BaseDraw {
  constructor(options) {
    super(options);
    this.currentDrawId = ""; // 当次绘制的-id
    this.labelEntity = null; // 标签实例
    this.pointEntity = null; // 点实例
    this.positionList = []; // 当次绘制的笛卡尔数组
  }
  resetDraw() {
    this.currentDrawId = this.generateUUID(); // 当次绘制的-id
    this.labelEntity = null; // 当次绘制的-圆实例
    this.pointEntity = null; // 当次绘制的-圆实例
    this.positionList = []; // 当次绘制的笛卡尔数组
  }
  addEntityCollection(entity) {
    this.entityCollection.add(entity, this.currentDrawId);
  }
  getAllEntity() {
    return this.entityCollection.getAll();
  }
  createPointEntity(cartesian) {
    const entity = new Cesium.Entity({
      position: cartesian, // 世界坐标
      point: {
        color: Cesium.Color.YELLOW,
        pixelSize: 5,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
      },
    });

    return entity;
  }
  createLabelEntity(cartesian, height) {
    const _this = this;
    return new Promise(async (resolve, reject) => {
      try {
        // 请求地形高程数据
        const entity = new Cesium.Entity({
          position: cartesian, // 世界坐标
          label: {
            text: `高度差:${height.toFixed(2)}米`,
            font: "20px",
            color: Cesium.Color.RED,
            pixelOffset: new Cesium.Cartesian2(0, -20),
            fillColor: Cesium.Color.WHITE,
            showBackground: true,
            backgroundColor: Cesium.Color.BLUE,
          },
        });
        resolve(entity);
      } catch (e) {
        console.error(e);
        reject(e);
      }
    });
  }
  // 计算两点高度差
  compuedHeight(point0, point1) {
    const p0 = this.ellipsoid.cartesianToCartographic(point0);
    const p1 = this.ellipsoid.cartesianToCartographic(point1);
    const height = Math.abs(p0.height - p1.height);
    return height;
  }
  createLabelEntity2(cartesian, pickedPosition) {
    return new Promise(async (resolve, reject) => {
      try {
        console.log("pickedPosition", pickedPosition);
        const cartographic = Cesium.Cartographic.fromCartesian(pickedPosition);
        console.log("cartographic", cartographic);
        // 请求地形高程数据
        let height = 0.0;
        if (this.viewer.terrainProvider) {
          const updatedPositions = await Cesium.sampleTerrainMostDetailed(
            this.viewer.terrainProvider,
            [cartographic]
          );
          console.log("updatedPositions", updatedPositions);
          height = updatedPositions[0].height;
        }
        console.log(`点击位置的高程为：${height} 米`);
        const entity = new Cesium.Entity({
          position: cartesian, // 世界坐标
          label: {
            text: `高度:${height}米`,
            font: "20px",
            color: Cesium.Color.RED,
            pixelOffset: new Cesium.Cartesian2(0, -20),
            fillColor: Cesium.Color.WHITE,
            showBackground: true,
            backgroundColor: Cesium.Color.BLUE,
          },
        });

        resolve(entity);
      } catch (e) {
        console.error(e);
        reject(e);
      }
    });
  }
}
/**
 * 开始绘制点
 * @param {* 是否显示测量Label} showMeasureLabel
 * @param {* 是否连续绘制} continuousDraw
 */
DrawPointHeight.prototype.startDraw = function (
  showMeasureLabel = true,
  continuousDraw = true
) {
  const _this = this;
  this._tip.show("单击开始绘制");
  this.resetDraw(); // 重置绘制中间量
  const customType = this.customType; // 自定义事件类型
  // 通过事件管理器新增事件 -左键单击事件
  this._handler.addHandelEvent(
    async (event) => {
      const cartesian = this._coorder.ScreenToCartesian3(event.position); // 屏幕坐标转世界坐标
      if (!Cesium.defined(cartesian)) return;
      _this.positionList.push(cartesian.clone());
      const length = _this.positionList.length;
      if (length > 0 && length % 2 === 0) {
        console.log("偶数点");
        if (showMeasureLabel) {
          // 每两个点，计算高度差
          const height = _this.compuedHeight(
            _this.positionList[length - 2],
            _this.positionList[length - 1]
          );
          // 标注实体
          _this.labelEntity = await _this.createLabelEntity(cartesian, height);
          _this.addEntityCollection(_this.labelEntity); // 加入集合
        }
      }
      // 点实体
      _this.pointEntity = _this.createPointEntity(cartesian);
      _this.addEntityCollection(_this.pointEntity); // 加入集合

      if (!continuousDraw) {
        // 不连续绘制
        _this.endDraw();
      }
    },
    customType,
    Cesium.ScreenSpaceEventType.LEFT_CLICK
  );
  // 通过事件管理器新增事件 -鼠标移动事件
  this._handler.addHandelEvent(
    (event) => {
      const { x, y } = event.endPosition;
      this._tip.moveTipDOMPosition(x, y); // 改变 TipDOM 位置
    },
    customType,
    Cesium.ScreenSpaceEventType.MOUSE_MOVE
  );
  // 通过事件管理器新增事件 -右键单击事件
  this._handler.addHandelEvent(
    () => {
      _this.endDraw();
    },
    customType,
    Cesium.ScreenSpaceEventType.RIGHT_CLICK
  );
};

/**
 * 结束绘制点
 */
DrawPointHeight.prototype.endDraw = function () {
  this._tip.close();
  // 移除绑定的事件
  const customType = this.customType;
  this._handler.removeHandelEvnet(
    customType,
    Cesium.ScreenSpaceEventType.LEFT_CLICK
  );
  this._handler.removeHandelEvnet(
    customType,
    Cesium.ScreenSpaceEventType.MOUSE_MOVE
  );
  this._handler.removeHandelEvnet(
    customType,
    Cesium.ScreenSpaceEventType.RIGHT_CLICK
  );
  this.resetDraw(); // 重置绘制中间量
};
/**
 * 清除绘制的点
 */
DrawPointHeight.prototype.removeDraw = function () {
  this.entityCollection.removeAll(); // 清空集合所有
};
